<template>
  <div class="chart-container">
    <h3 class="chart-container__title">{{ title }}</h3>
    <div ref="chartRef" class="chart-container__chart">
      <div v-if="!options" class="chart-loading">
        正在加载图表...
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'

interface Props {
  title: string
  options: any
  autoResize?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  autoResize: true
})

const chartRef = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
  if (!chartRef.value || !props.options) return
  
  chartInstance = echarts.init(chartRef.value)
  chartInstance.setOption(props.options)
}

const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

watch(() => props.options, (newOptions) => {
  if (chartInstance) {
    chartInstance.setOption(newOptions)
  }
}, { deep: true })

onMounted(() => {
  initChart()
  
  if (props.autoResize) {
    window.addEventListener('resize', resizeChart)
  }
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  if (props.autoResize) {
    window.removeEventListener('resize', resizeChart)
  }
})
</script>

<style scoped>
.chart-container {
  background: rgba(30, 58, 95, 0.6);
  border: 1px solid rgba(74, 144, 226, 0.3);
  border-radius: 8px;
  padding: 20px;
  backdrop-filter: blur(10px);
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chart-container__title {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #4a90e2;
  border-bottom: 1px solid rgba(74, 144, 226, 0.3);
  padding-bottom: 10px;
}

.chart-container__chart {
  flex: 1;
  min-height: 200px;
  position: relative;
}

.chart-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #4a90e2;
  font-size: 14px;
  text-align: center;
}
</style>